package com.sinszm.web.request;

import com.sinszm.web.support.RequestUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;

/**
 * 重定义流处理
 *
 * @author chenjianbo
 */
public class MRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    MRequestWrapper(HttpServletRequest request) {
        super(request);
        this.body = RequestUtils.requestBody(request).getBytes();
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream bs = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }

            @Override
            public int read() {
                return bs.read();
            }
        };
    }

}
